<template>
	<view class="">
		<u-navbar title="提交订单" title-color="#FFF" back-icon-color="#FFF" :background="bc" :border-bottom="false">
		</u-navbar>
		<img src=".../../static/background-image.png" style="position: absolute;top: 0;width: 100%;"
			mode="widthFix"></img>
		<view class="content-box pr " style="overflow: hidden;">
			<view class="pr loging" v-if="logingBox">
				<ourLoading :active="logingBox" translateY="50" color="#48A147" background-color="white" size="4">
				</ourLoading>
			</view>
			<template v-else>
				<Address :addressInfo="addressInfo" :time="time"></Address>
				<view class="mt30 bgcf pb12 bdr20 m30" style="border-radius: 20rpx;line-height: 66rpx;">
					<view class="p24" style="padding-bottom: 0;">
						<view class="df jcsb aic fs26 ">
							<text class="c6 fwb">发车时间</text>
							<view class="df aic" >
								<!-- 预计{{hopeTime}}之前送达 -->
								<u-input @click="handleTime" v-model="hopeTime" placeholder="请选择期发车时间" disabled  input-align="right"></u-input>
								<nmr-icon  name="xiangyou1" size="28" style="margin-left: auto;"
									color="#666666"></nmr-icon>
							</view>
						</view>
						
					</view>
				</view>
				<!-- 下单商品信息 -->
				<GoodsInfo @change="changeRemark" :lengthGood="goodsList.length" :goodsList="newGoodsList" :isHaveStock="isHaveStock"></GoodsInfo>
				<!-- 下单金额相关 -->
				<orderPrice @FeePrice="showFeePrice = true" @feeInfo="feeInfoShow = true"  :isHaveStock="isHaveStock" :currentInfoCoupon="currentInfoCoupon" :couponList="couponList"
					@handleCoupon="showCoupon = true" :payAmountFee="payAmountFee" :priceAll="priceAll"
					:deliveryFee="deliveryFee"></orderPrice>
				<Other ref="other"></Other>
				<payBtn :isHaveStock="isHaveStock" :loading="loading" @handlesubmit="handlesubmit" :payPrice="payAmountFee"></payBtn>
				<view v-if="!loadingSkeleton" class="mdbJr" style="height: 200rpx;"></view>
			</template>
		</view>
		<popupConfirm @handleChoose="handleChoose" :couponList="couponList" v-model="showCoupon"></popupConfirm>
		<ModalMsg v-model="sctokShow" confirmName="我知道了" @confirm="chooseSctok" :showCancel="false">
			<view class="address-desc mt30 fs26 c3 u-text-center">
				当前库存不足，请下预约单
				<!-- 	<view class="">
					我知道了
				</view> -->
			</view>
		</ModalMsg>
		<u-select  title='发车时间'  v-model="showTime" :list="hopeTimeList" @confirm="confirmTime"></u-select>
		<modal :errorInfo="errorInfo" @onOk="modalOk" :showToast="showToast" @cancel="modalCancel" ref="modal"></modal>
		<ModalMsg width="680" v-model="feeInfoShow" title="配送费说明" :showCancel="false">
			<view class=" mt30 fs26 c3 p020 u-text-left" style="line-height: 60rpx;">
				<view class="">
					1、采购满平台设置的起送费后方可下单。
				</view>
				<view class="">
					2、配送费=基础配送费+超重配送费，例如：货物重量在<text class="app-theme">20kg</text>以内仅收取基础配送费<text class="price">8</text>元，超出部分，加收<text class="price">0.3</text>元/kg(不足<text class="app-theme">1</text>按<text class="app-theme">1</text>kg收取)。
				</view>
				<view class="">
					3、不同城市或者不同地址的基础配送费和加收费用可能不同，请以小程序的实际显示为准。
				</view>
			</view>
		</ModalMsg>
		<FeePricePopup :isAir="false" @feeInfo="feeInfoShow = true" :goodsList="orderChildList" v-model="showFeePrice" :infoByAreaIdFee="infoByAreaIdFee" :platformFeeInfo="checkFeeInfo('')"></FeePricePopup>
	</view>
</template>
<script>
	import Decimal from "decimal.js";
	import Address from './components/Address.vue'
	import GoodsInfo from './components/GoodsInfo.vue'
	import orderPrice from './components/orderPrice.vue'
	import popupConfirm from './components/popupConfirm.vue'
import ModalMsg from '@/components/ModalMsg.vue'
	import Other from './components/Other.vue'
	import ourLoading from '@/components/our-loading/our-loading.vue'
	import modal from '@/components/modal/modal.vue'
	import FeePricePopup from '../shopping/components/FeePricePopup.vue'
	import payBtn from './components/payBtn.vue'
	import navBg from "@/static/background-image.png"
	import {
		shopAccountDetail
	} from "@/api/address.js"
	import {
		memberCouponOrderList
	} from '@/api/coupon.js'
	import {
		getInfoOther,
		getSendMoney,
		shopPurOrderAdd,
		combineInsertByBoFromB,
		insertBPrePurOrder,
		getSendTime
	} from "@/api/order.js"

	export default {
		components: {
			ModalMsg,
			Address,
			GoodsInfo,
			orderPrice,
			payBtn,
			Other,
			ourLoading,
			popupConfirm,
			modal,
			FeePricePopup
		},
		data() {
			return {
				feeInfoShow:false,
				showFeePrice:false,
				sctokShow: false,
				showCoupon: false,
				bc: {
					backgroundImage: `url(${navBg})`,
					backgroundSize: '100%',
					backgroundRepeat: 'no-repeat',
				},
				addressId: '',
				goodsList: [],
				addressInfo: {}, //地址信息
				logingBox: true,
				sysTimeInfo: {},
				time: '',
				priceAll: 0,
				deliveryFee: 0,
				loading: false,
				couponList: [],
				currentInfoCoupon: {
					conditionMoney: 0,
					reduceMoney: 0,
					memberCouponId: ''
				},
				remark: '',
				flag: '',
				isHaveStock:1,
				errorInfo:{},
				showToast:false,
				showTime:false,
				hopeTime:'17:00',
				newGoodsList:[],
				infoByAreaIdFee: {
					sendMoney: 0,
					childList:[]
				},
				hopeTimeList:[],
				orderChildList:[]

			}
		},
		computed: {
			payAmountFee() {
				let priceAll = new Decimal(this.priceAll);
				let coupon = new Decimal(this.currentInfoCoupon.reduceMoney || 0);
				const deliveryFee = new Decimal(Number(this.deliveryFee));
				return new Decimal(priceAll.add(deliveryFee).sub(coupon)).toFixed(2)
			}
		},
		watch: {
			goodsList: {
				handler(e) {
					this.priceAll = 0
					e.forEach(i => {
						this.numAll += i.purNum
						if (i.checkFlag) {
							let price = i.purNum * i.platformPrice
							this.priceAll = Math.round((this.priceAll + price) * 100) / 100
						}
					})

				},
				immediate: true,
				deep: true
			}
		},
		async onLoad(e) {
			this.addressId = e.addressId
			if (e.flag == "theme") {
				this.goodsList = JSON.parse(decodeURIComponent(e.goodsList))
				this.isHaveStock = Number(e.stcok) //区分是否是预约单 0代表没有库存是预约单 1反之
			} else {
				this.goodsList = uni.getStorageSync('CARGOODLIST').filter(item => item.checkFlag)
			}
			this.newGoodsList = this.filterArrayBysupplierId(this.goodsList)
			console.log(this.newGoodsList,'this.newGoodsList')
			
			
			
			
			
			
			this.flag = e.flag
			await this.getSendTime()
			await this.getAddressInfo()
			await this.getInfoOther()
			await this.getmemberCouponOrderList()
			this.logingBox = false

			
		},
		mounted() {
			uni.$on("handelAddress", async (res) => {
				this.addressInfo = res
				this.infoByAreaId()
			})
		},
		onUnload() {
			uni.$off("handelAddress", () => {});
		},
		methods: {
			checkFeeInfo(e){
				let info = {
							sendLimit:0,
							diff:0
						}
				if(this.infoByAreaIdFee.childList.length&&this.infoByAreaIdFee.childList.find(_e =>_e.sign==e)){
					let res = this.infoByAreaIdFee.childList.find(_e =>_e.sign==e)
					return {
						sendLimit:res.sendLimit||0,
						diff:res.diff||0
					}
				}else{
					return info
				}
			},
			changeRemark(e,i){
				this.newGoodsList[i].remark = e
			},
			getSendTime(){
			return	getSendTime({areaId: this.LOCATION.areaId}).then(res =>{
					if(res.code==200){
						this.hopeTimeList = res.data.map(item =>{
							return {
								label: item.name,
								value: item.value
							}
						})
						if(res.data.length){
							this.hopeTime = res.data[0].value
						}
					}else{
						uni.showToast({
							title:res.msg,
							icon:'none',
							mask:true
						})
					}
				})
			},
			filterArrayBysupplierId(arr) {
				const filteredArray = [];
				const groupedData = {};
				for (const item of arr) {
					const supplierId = item.supplierId||'';
					const supplierName = item.supplierName||'宅美自营';
					if (!groupedData[supplierId]) {
						groupedData[supplierId] = {
							goodsList:[],
							supplierName:supplierName,
							supplierId:supplierId,
							shopPurOrderDetails:[],
							isSelfSend:item.isSelfSend,
							platformMoney:0,
							remark:''
						};
					}
					const shopMoney = new Decimal(item.purNum||0).mul(new Decimal(item.platformPrice||0)).toFixed(2)
					
					let info = {
						platformGoodsSpecMixId: item.platformGoodsSpecMixId,
						saleNum: item.purNum,
						platformMoney: shopMoney,
						platformPrice: item.platformPrice,
						busType :item.busType||'',
						supplierPrice:item.supplierPrice||0,
						isSelfSend:item.isSelfSend||''
					}
					groupedData[supplierId].platformMoney = new Decimal(groupedData[supplierId].platformMoney).add(shopMoney)
					groupedData[supplierId].shopPurOrderDetails.push(info);
					groupedData[supplierId].goodsList.push(item);
				}
				for (const key in groupedData) {
					filteredArray.push(groupedData[key]);
				}
				return this.sortArray(filteredArray);
			},
			sortArray(arr){
				 let sortedArr = [];
				 let id2Arr = [];
				 let idNot2Arr = [];
				 for (let obj of arr) {
					 let isSelfSend = obj.goodsList[0].isSelfSend
					 let supplierId = obj.supplierId
				   if (isSelfSend ==0 && supplierId== '') {
				     sortedArr.push(obj);
				   } else if (isSelfSend ==0 && supplierId !== '') {
				     idNot2Arr.push(obj);
				   } else {
				     id2Arr.push(obj); 
				   }
				 }
				 sortedArr = sortedArr.concat(idNot2Arr, id2Arr); // 拼接三个数组
				return sortedArr
			},
			handleTime(e){
				this.showTime = true
			},
			confirmTime(e){
				this.hopeTime = e[0].value
				
			},
			handleChoose(e) {
				this.currentInfoCoupon = e
			},
			// 获取优惠券列表
			getmemberCouponOrderList() {
				let shopPurOrderDetails = this.goodsList.map(item => {
					const shopMoney = new Decimal(item.purNum).mul(new Decimal(item.platformPrice)).toFixed(2)
					return {
						platformGoodsSpecMixId: item.platformGoodsSpecMixId,
						saleNum: item.purNum,
						platformMoney: shopMoney,
						platformPrice: item.platformPrice,
					}
				})
				if (!shopPurOrderDetails.length) {
					this.$u.toast('商品校验失败')
					this.loading = false
					return
				}
				return memberCouponOrderList({
					shopPurOrder: {
						addressId: this.addressInfo ? this.addressInfo.addressId : '',
						sendMoney: this.deliveryFee || 0,
						platformMoney: this.priceAll,
						payMoney: this.payAmountFee,
						shopPurOrderDetails,
					}
				}).then(res => {
					if (res.code == 200) {
						this.couponList = res.data
						if (res.data.length) {
							let info = res.data.find(e => e.isCanUse == 1)
							if (info) {
								this.currentInfoCoupon = info
							}
						}
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							mask: true
						})
					}
				})
			},
			async handlesubmit() {
				if (!(this.addressInfo && this.addressInfo.addressId) && this.sendType == 2) {
					uni.showToast({
						title: '请选择地址',
						icon: "none",
					});
					return;
				}
				if (this.$refs.other.isBeforeNotice == 1 && !this.$refs.other.beforeNotice) {
					uni.showToast({
						title: '请输入提前通知时间(分钟)',
						icon: "none",
					});
					return
				}
				this.purOrder()
			},
			chooseSctok() {
				uni.$emit('isRefresh', 0)
				uni.navigateBack({
					delta: 1
				})
			},
			purOrder() {
				this.loading = true
				let shopPurOrderDetails = this.goodsList.map(item => {
					const shopMoney = new Decimal(item.purNum).mul(new Decimal(item.platformPrice)).toFixed(2)
					return {
						platformGoodsSpecMixId: item.platformGoodsSpecMixId,
						saleNum: item.purNum,
						platformMoney: shopMoney,
						busType :item.busType||'',
						platformPrice: item.platformPrice,
						supplierPrice:item.supplierPrice||0,
						isSelfSend:item.isSelfSend||''
					}
				}) 
			
				
				if (!this.hopeTime) {
					this.$u.toast('请选择发车时间')
					this.loading = false
					return
				}
				if (!shopPurOrderDetails.length) {
					this.$u.toast('商品校验失败')
					this.loading = false
					return
				}
				// let goodsList = uni.getStorageSync('CARGOODLIST').filter(item => !item.checkFlag)
				// this.$u.vuex('CARGOODLIST', JSON.parse(JSON.stringify(goodsList)))
				// uni.setStorageSync('CARGOODLIST', JSON.parse(JSON.stringify(goodsList)))
				if (this.flag == 'theme') {
					insertBPrePurOrder({
						supplierId:this.goodsList[0].supplierId,
						hopeTime:this.hopeTime,
						addressId: this.addressInfo ? this.addressInfo.addressId : '',
						sendMoney: this.deliveryFee || 0,
						platformMoney: this.priceAll,
						payMoney: this.payAmountFee,
						shopPurOrderDetails,
						isNeedReceipt: this.$refs.other.isNeedReceipt ? 1 : 0, //是否需要小票 1需要 0不需要
						isBeforeNotice: this.$refs.other.isBeforeNotice ? 1 : 0, //是否需要提前通知 1需要 0不需要
						isTrust: this.$refs.other.isTrust ? 1 : 0, //信任签收 1开启 0关闭
						remark: this.remark,
						beforeNotice: this.$refs.other.beforeNotice,
						memberCouponId: this.currentInfoCoupon.memberCouponId,
						discountMoney: this.currentInfoCoupon.reduceMoney || 0,
						isPreSale: 1,
						isHaveStock: this.isHaveStock, //0没库存 走预约单 1反之
						auditStatus: this.isHaveStock ,//有库存传1没有库存传0
						isKp:1
					}).then(res => {
						if (res.code == 200) {
							this.loading = false
							let priceInfo = {
								platformMoney: this.payAmountFee,
								sendMoney: this.deliveryFee || 0,
								goodsMoney: this.priceAll || 0,
							}
							let goodsList = uni.getStorageSync('CARGOODLIST').filter(item => !item.checkFlag)
							uni.setStorageSync('CARGOODLIST', JSON.parse(JSON.stringify(goodsList)))
							if (this.isHaveStock == 1) {
								uni.redirectTo({
									url: '/pages/confirm/payPage?orderId=' + res.data.shopPurOrderId +
										'&priceInfo=' + JSON.stringify(priceInfo) + '&szbankOpen=' + res
										.data.szbankOpen
								})
							} else {
								uni.reLaunch({
									url: '/pages/order/order?current=' + 0
								})
							}

						} else {
							this.loading = false
							if (res.msg == '库存不足') {
								this.sctokShow = true
							} else {
								this.calcError(res)
							}

						}
					})
				} else {
					shopPurOrderAdd({
						supplierId:this.goodsList[0].supplierId,
						hopeTime:this.hopeTime,
						addressId: this.addressInfo ? this.addressInfo.addressId : '',
						sendMoney: this.deliveryFee || 0,
						platformMoney: this.priceAll,
						payMoney: this.payAmountFee,
						shopPurOrderList:this.newGoodsList,
						shopPurOrderDetails,
						isNeedReceipt: this.$refs.other.isNeedReceipt ? 1 : 0, //是否需要小票 1需要 0不需要
						isBeforeNotice: this.$refs.other.isBeforeNotice ? 1 : 0, //是否需要提前通知 1需要 0不需要
						isTrust: this.$refs.other.isTrust ? 1 : 0, //信任签收 1开启 0关闭
						remark: this.remark,
						beforeNotice: this.$refs.other.beforeNotice,
						memberCouponId: this.currentInfoCoupon.memberCouponId,
						discountMoney: this.currentInfoCoupon.reduceMoney || 0,
						isPreSale: 0,
						isHaveStock: 1,
						isKp:1
					}).then(res => {
						if (res.code == 200) {
							this.loading = false
							let priceInfo = {
								platformMoney: this.payAmountFee,
								sendMoney: this.deliveryFee || 0,
								goodsMoney: this.priceAll || 0,
							}
							let goodsList = uni.getStorageSync('CARGOODLIST').filter(item => !item.checkFlag)
							uni.setStorageSync('CARGOODLIST', JSON.parse(JSON.stringify(goodsList)))
							uni.redirectTo({
								url: '/pages/confirm/payPage?orderId=' + res.data.shopPurOrderId +
									'&priceInfo=' + JSON.stringify(priceInfo) + '&szbankOpen=' + res.data
									.szbankOpen
							})
						} else {
							this.loading = false
							this.calcError(res)
						}
					})
				}

			},
			combineInsertByBoFromB(){
				
			},
			calcError(res){
				if(res.code!=4003){
					uni.showModal({
						title: '温馨提示',
						content: res.msg,
						confirmText: '重新下单',
						confirmColor: "#48A147",
						success: function(res) {
							if (res.confirm) {
								console.log('用户点击确定');
								uni.navigateBack()
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}else {
					this.errorInfo = JSON.parse(res.msg)
					this.showToast = true
				}
			},

			getInfoOther() {
				return getInfoOther({
					strategyPresaleId: 2
				}).then(res => {
					if (res.code == 200) {
						this.sysTimeInfo = res.data
						let now = this.$moment(new Date()).format('YYYY-MM-DD HH:mm')
						let end = this.$moment(new Date()).format('YYYY-MM-DD ') + this.sysTimeInfo.orderLimitTime
						let isday = this.$moment(now).isAfter(end, 'minutes') //是否在截止时间外
						const addTime = Number(this.sysTimeInfo.arriveLimitTime) + (isday ? 1 : 0)
						this.time = this.$moment(new Date).add(addTime, 'days').format('YYYY-MM-DD')
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							mask: true
						})
					}
				})

			},
			infoByAreaId() {
				uni.showLoading({
					title:'加载中...',
					mask:true
				})
				let orderChildList = []
				const groupedData = {};
				for (const item of this.newGoodsList) {
					const supplierId = item.goodsList[0].isSelfSend==0?'':item.goodsList[0].supplierId;
					if (!groupedData[supplierId]) {
						groupedData[supplierId] = {
							goodsList:[],
							isSelfSend: item.goodsList[0].isSelfSend,
							platformMoney:0,
							sign: item.goodsList[0].isSelfSend==0?'':item.supplierId
						};
					}
					let list = item.goodsList.map(e =>{
						let price = new Decimal(e.purNum).mul(new Decimal(e.platformPrice||0))
						groupedData[supplierId].platformMoney = new Decimal(groupedData[supplierId].platformMoney).add(price)
						return  {saleNum:e.purNum,platformGoodsSpecMixId:e.platformGoodsSpecMixId,image:e.image}
					})
					groupedData[supplierId].goodsList.push(...list);
				}
				for (const key in groupedData) {
					orderChildList.push(groupedData[key]);
				}
				this.orderChildList  = orderChildList
				let params = {
					areaId: this.LOCATION.areaId,
					orderChildList:orderChildList
				}
				return getSendMoney(params).then(res => {
					uni.hideLoading()
					if (res.code == 200) {
						this.newGoodsList.forEach(item =>{
							item.sendMoney = res.data.childList.find(i =>(i.sign==item.supplierId)||item.isSelfSend==0).sendMoney
						})
						this.infoByAreaIdFee = res.data
						this.deliveryFee = res.data.sendMoney || 0
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							mask: true
						})
					}
				})
			},
			modalOk(){
				let priceInfo = {
					platformMoney: this.errorInfo.changePlatformMoney,
					sendMoney:  0,
					goodsMoney: this.errorInfo.changePlatformMoney || 0,
				}
				uni.redirectTo({
					url: '/pages/confirm/payPage?isLess=true&orderId=' + this.errorInfo.shopPurOrderChangeLogId + '&priceInfo=' + JSON
						.stringify(priceInfo) + '&szbankOpen=true'
				})
			},
			modalCancel(){
				uni.navigateTo({
					url: `/pages/order/refundDetail?id=${this.errorInfo.shopPurOrderChangeLogId}&type=detail`
				})
			},
			getAddressInfo() {
				return shopAccountDetail(this.addressId).then(res => {
					if (res.code == 200) {
						this.addressInfo = res.data
						this.infoByAreaId()
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							mask: true
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.loging {
		height: calc(100vh - 48px - var(--status-bar-height));
	}
</style>